import NProgress from '@/utils/nprogress'
import router from '@/router'

/**
 * 路由守卫
 */
export function setupPermission() {
  const permissionStore = usePermissionStore()
  NProgress.start() // NProgress Configuration
  const whiteList = ['/login'] // no redirect whitelist
  router.beforeEach(async (to, from, next) => {
    // 开始进度条
    NProgress.start()
    // 设置页面标题
    document.title = await getPageTitle()
    const hasToken = getCookieAccessToken()
    // 确认用户是否已登录
    if (hasToken) {
      if (to.path === '/login') {
        // 如果已登录，则重定向到主页
        next({ path: '/' })
        NProgress.done()
      } else {
        // 判断是否拥有权限
        // const hasRoles = permissionStore.listPermission && permissionStore.listPermission.length > 0
        if (permissionStore.isGetMenu) {
          next()
        } else {
          try {
            // 刷新页面时，如果当前路由不在当前菜单中定位到首页
            let have = false
            const accessedRoutes = await permissionStore.generateRoutes()
            accessedRoutes.forEach(route => {
              router.addRoute(route)
            })
            for (let i = 0; i < accessedRoutes.length; i++) {
              if (accessedRoutes[i].children) {
                for (let j = 0; j < accessedRoutes[i].children.length; j++) {
                  if (accessedRoutes[i].children[j].path === to.path) {
                    have = true
                    break
                  }
                }
              }
            }
            if (have) {
              next({ ...to, replace: true })
            } else {
              next()
            }
          } catch (error) {
            // 删除令牌，然后转到登录页面重新登录
            useUserStore().userStore.resetUserStore()
            console.error(error)
            Emessage('error', error || 'Has Error')
            // next(`/login?redirect=${ to.path }`)
            redirectToLogin(to, next)
            NProgress.done()
          }
        }
      }
    } else {
      if (whiteList.indexOf(to.path) !== -1) {
        // 在登录白名单中，直接进入
        next()
      } else {
        // 其他没有访问权限的页面被重定向到登录页面。
        // next(`/login?redirect=${ to.path }`)
        redirectToLogin(to, next)
        NProgress.done()
      }
    }
  })

  router.afterEach(() => {
    // finish progress bar
    NProgress.done()
  })
}

/** 重定向到登录页 */
function redirectToLogin(to, next) {
  const params = new URLSearchParams(to.query)
  const queryString = params.toString()
  const redirect = queryString ? `${ to.path }?${ queryString }` : to.path
  next(`/login?redirect=${ encodeURIComponent(redirect) }`)
}

/** 判断是否有权限 */
export function hasAuth(value) {
  const auths = usePermissionStore().listPermission
  return typeof value === 'string'
    ? auths.includes(value)
    : value.some((perm) => auths.includes(perm))
}
